package com.clannad.eduservice.controller.Front;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clannad.commonutils.CourseWebVoOrder;
import com.clannad.commonutils.JwtUtils;
import com.clannad.commonutils.R;
import com.clannad.eduservice.entity.EduCourse;
import com.clannad.eduservice.entity.chapter.ChapterVo;
import com.clannad.eduservice.entity.frontVo.CourseFrontVo;
import com.clannad.eduservice.entity.frontVo.CourseWebVo;
import com.clannad.eduservice.feign.OrderClient;
import com.clannad.eduservice.service.EduChapterService;
import com.clannad.eduservice.service.EduCourseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/eduservice/coursefront")
@CrossOrigin
public class CourseFrontController {

    @Autowired
    private EduCourseService eduCourseService;
    @Autowired
    private EduChapterService eduChapterService;
    @Autowired
    private OrderClient orderClient;

    @PostMapping("getFrontCourseList/{page}/{limit}")
    public R getFrontCourseList(@PathVariable long page, @PathVariable long limit, @RequestBody(required = false) CourseFrontVo courseFrontVo){
        Page<EduCourse> pageCourse=new Page<>(page,limit);
        Map<String,Object> map=eduCourseService.getCourseForntList(pageCourse,courseFrontVo);
        return R.ok().data(map);
    }

    @GetMapping("getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request){
        CourseWebVo courseWebVo=eduCourseService.getBaseCourseInfo(courseId);
        List<ChapterVo> chapterVideoByCourseId = eduChapterService.getChapterVideoByCourseId(courseId);
        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(request);
        if(!StringUtils.isEmpty(memberIdByJwtToken)){
            boolean buyCourse = orderClient.isBuyCourse(courseId,memberIdByJwtToken);
            return R.ok().data("courseWebVo",courseWebVo).data("chapterVideoList",chapterVideoByCourseId).data("isBuy",buyCourse);
        }
        else{
            return R.ok().data("courseWebVo",courseWebVo).data("chapterVideoList",chapterVideoByCourseId).data("isBuy",false);
        }


    }

    @PostMapping("getCourseInfoORder/{courseId}")
    public CourseWebVoOrder getCourseInfoORder(@PathVariable String courseId){
        CourseWebVo baseCourseInfo = eduCourseService.getBaseCourseInfo(courseId);
        CourseWebVoOrder courseWebVoOrder=new CourseWebVoOrder();
        BeanUtils.copyProperties(baseCourseInfo,courseWebVoOrder);
        return courseWebVoOrder;
    }
}
